package com.pyue.eam.regi.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pyue.eam.admin.api.entity.regi.CqRegiLibEntity;
import com.pyue.eam.admin.api.except.ApiAsserts;
import com.pyue.eam.app.api.entity.AppUser;
import com.pyue.eam.app.mapper.AppUserMapper;
import com.pyue.eam.common.security.util.SecurityUtils;
import com.pyue.eam.regi.bo.CqRegiUserEntity;
import com.pyue.eam.regi.mapper.CqRegiLibMapper;
import com.pyue.eam.regi.mapper.CqRegiUserMapper;
import com.pyue.eam.regi.service.CqRegiLibService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 团长表
 *
 * @author lucc
 * @date 2023-10-12 20:38:50
 */
@Service
@AllArgsConstructor
public class CqRegiLibServiceImpl extends ServiceImpl<CqRegiLibMapper, CqRegiLibEntity> implements CqRegiLibService {
    private final CqRegiUserMapper cqRegiUserMapper;
    private final AppUserMapper appUserMapper;

    @Override
    public CqRegiLibEntity getRegiLibByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        return baseMapper.getRegiByUserId(userId);
    }

    @Override
    public Long updateRegiInfo(CqRegiLibEntity cqRegiLib) {
        Long id = cqRegiLib.getRegiId();
        if (id == null) {
            CqRegiLibEntity tenantCompanyInfo = baseMapper.getRegiByUserId(SecurityUtils.getUserId());
            if (tenantCompanyInfo == null || tenantCompanyInfo.getRegiId() == null) {
                save(cqRegiLib);
            } else {
                updateById(cqRegiLib.setRegiId(tenantCompanyInfo.getRegiId()));
            }
        } else {
            updateById(cqRegiLib);
        }
        return cqRegiLib.getRegiId();
    }

    @Override
    public List<CqRegiUserEntity> memberList(Long regiId) {
        regiId = getCurrentRegiId(regiId);

        // 查询团长成员列表
        List<CqRegiUserEntity> regiUserList = cqRegiUserMapper.selectList(Wrappers.lambdaQuery(CqRegiUserEntity.class)
                .eq(CqRegiUserEntity::getRegiId, regiId));

        // 根据regiId查询团长成员列表
        if (CollUtil.isNotEmpty(regiUserList)) {
            regiUserList.forEach(e -> {
                AppUser appUser = appUserMapper.selectById(e.getUserId());
                if (e.getUserId() != null) {
                    e.setAppUser(appUser);
                }
                if (StrUtil.isBlank(e.getUserAvatar())) {
                    e.setUserAvatar(appUser.getAvatar());
                }
            });
        }

        return regiUserList;
    }

    private Long getCurrentRegiId(Long regiId) {
        // 如果regiId为空，则从数据库中获取
        if (regiId == null) {
            CqRegiLibEntity libEntity = getRegiLibByUserId(SecurityUtils.getUserId());
            ApiAsserts.isTrue(libEntity != null, "请先完善团长信息");
            assert libEntity != null;
            regiId = libEntity.getRegiId();
        }
        return regiId;
    }

    /**
     * 非团队成员
     *
     * @param regiId 团id
     * @return 团队成员
     */
    @Override
    public List<CqRegiUserEntity> dealMemberList(Long regiId) {
        regiId = getCurrentRegiId(regiId);
        List<Long> userIdList = cqRegiUserMapper.getUserIdListByRegiId(regiId);

        List<AppUser> appUserList;
        if (CollUtil.isNotEmpty(userIdList)) {
            appUserList = appUserMapper.selectList(Wrappers.lambdaQuery(AppUser.class)
                    .eq(AppUser::getRoleTypeId, "3")
                    .notIn(AppUser::getUserId, userIdList));
        } else {
            appUserList = appUserMapper.selectList(Wrappers.lambdaQuery(AppUser.class).eq(AppUser::getRoleTypeId, "3"));
        }

        final Long userId = SecurityUtils.getUserId();
        if (CollUtil.isNotEmpty(appUserList)) {
            return appUserList.stream().filter(e -> !Objects.equals(e.getUserId(), userId)).map(e -> {
                CqRegiUserEntity cqRegiUser = new CqRegiUserEntity();
                cqRegiUser.setAppUser(e);
                cqRegiUser.setUserAvatar(e.getAvatar());
                cqRegiUser.setScore("75");
                cqRegiUser.setUserId(e.getUserId());
                cqRegiUser.setCreateTime(LocalDateTime.now());
                return cqRegiUser;
            }).collect(Collectors.toList());
        } else {
            return CollUtil.newArrayList();
        }
    }

    @Override
    public Boolean batchJoinUserList(List<Long> userIdList) {
        ApiAsserts.isTrue(CollUtil.isNotEmpty(userIdList), "传参错误");
        Long currentRegiId = getCurrentRegiId(null);
        List<Long> readyUserIdList = cqRegiUserMapper.getUserIdListByRegiId(currentRegiId);
        List<Long> dealUserIdList = CollUtil.subtractToList(userIdList, readyUserIdList);

        if (CollUtil.isNotEmpty(dealUserIdList)) {
            cqRegiUserMapper.batchUserToRegi(currentRegiId, dealUserIdList);
        }

        return Boolean.TRUE;
    }

    @Override
    public AppUser regiUserInfo(Long userId) {
        return appUserMapper.selectById(userId);
    }

    @Override
    public Boolean updateRegiUserInfo(AppUser appUser) {
        return appUserMapper.updateById(appUser) > 0;
    }

    @Override
    public List<CqRegiLibEntity> regiListByWorkId(Long userId) {
        if (userId == null) {
            return CollUtil.newArrayList();
        }

        List<Long> regiIdList = cqRegiUserMapper.getRegiIdListByUserId(userId);
        if (CollUtil.isNotEmpty(regiIdList)) {
            return listByIds(regiIdList);
        }

        return CollUtil.newArrayList();
    }

    @Override
    public List<CqRegiLibEntity> dealRegiListByWorkId(Long userId) {
        if (userId == null) {
            return CollUtil.newArrayList();
        }

        List<Long> regiIdList = cqRegiUserMapper.getRegiIdListByUserId(userId);

        List<CqRegiLibEntity> list;
        if (CollUtil.isNotEmpty(regiIdList)) {
            list = list(Wrappers.lambdaQuery(CqRegiLibEntity.class).notIn(CqRegiLibEntity::getRegiId, regiIdList));
        } else {
            list = list(Wrappers.emptyWrapper());
        }

        return list.stream().filter(e -> !Objects.equals(e.getRegiId(), getCurrentRegiId(null))).collect(Collectors.toList());
    }

    @Override
    public Boolean batchJoinRegiList(Long userId, List<Long> regiIdList) {
        ApiAsserts.isTrue(CollUtil.isNotEmpty(regiIdList), "传参错误");
        List<Long> readyRegiIdList = cqRegiUserMapper.getRegiIdListByUserId(userId);
        List<Long> dealRegiIdList = CollUtil.subtractToList(regiIdList, readyRegiIdList);

        if (CollUtil.isNotEmpty(dealRegiIdList)) {
            cqRegiUserMapper.batchRegiToUser(userId, dealRegiIdList);
        }

        return Boolean.TRUE;
    }

}
